package com.codeant.bikeindicatorapplication;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.codeant.bikeindicatorapplication.tools.ClickFeedbackHelper;
import com.codeant.bikeindicatorapplication.tools.PublicVariables;
import com.codeant.bikeindicatorapplication.tools.SharedPreferencesHelper;
import com.codeant.bikeindicatorapplication.tools.SingleToast;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.text.DecimalFormat;

public class SsCalibrateActivity extends Activity implements SensorEventListener {
    private String TAG = "SsCalibrateActivity";

    private Button quit_btn;
    private TextView restart_tv;
    private TextView accel_data_tv;
    private TextView accel_old_data_tv;
    private Button ok_x_btn;
    private Button ok_y_btn;
    private SeekBar extent_seekBar;
    private Button ok_extent_btn;

    SensorManager sensorManager;//加速度传感器管理器
    Sensor sensor = null;//加速度传感器实例
    StringBuffer ACCELEROMETER_DATA;//加速度数据
    float ACCELEROMETER_X = 0;//X加速度数据
    float ACCELEROMETER_Y = 0;//Y加速度数据
    float ACCELEROMETER_Z = 0;//Z加速度数据
    float ACCELEROMETER_EXTENT = 0;//转弯幅度进度条数据

    private Integer TAG_BTN_QUIT = 1;
    private Integer TAG_OK_X_BTN = 2;
    private Integer TAG_OK_Y_BTN = 3;
    private Integer TAG_OK_EXTENT_BTN = 4;
    private Integer TAG_RESTART_TV = 5;

    private PublicVariables pubVari = new PublicVariables();
    SharedPreferencesHelper sph = new SharedPreferencesHelper();

    private boolean SHOW_REMIND_RESTART = false;//标记是否已弹出重启的提醒，避免重复弹出

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        sph.initSP(SsCalibrateActivity.this);//记得初始化
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ss_calibrate);
        
        initWidgets();
    }
    
    public void initWidgets(){
        quit_btn = (Button) findViewById(R.id.quit_btn_ss);
        restart_tv = (TextView) findViewById(R.id.restart_tv_ss);
        accel_data_tv = (TextView) findViewById(R.id.accel_data_tv_ss);
        accel_old_data_tv = (TextView) findViewById(R.id.accel_old_data_tv_ss);
        ok_x_btn = (Button) findViewById(R.id.ok_btn_ss);
        ok_y_btn = (Button) findViewById(R.id.ok_land_btn_ss);
        extent_seekBar = (SeekBar) findViewById(R.id.seekBar_ss);
        ok_extent_btn = (Button) findViewById(R.id.ok_extent_btn_ss);

        quit_btn.setOnClickListener(new ClickListeners());
        quit_btn.setTag(TAG_BTN_QUIT);

        restart_tv.setOnClickListener(new ClickListeners());
        restart_tv.setTag(TAG_RESTART_TV);

        ok_x_btn.setOnClickListener(new ClickListeners());
        ok_x_btn.setTag(TAG_OK_X_BTN);

        ok_y_btn.setOnClickListener(new ClickListeners());
        ok_y_btn.setTag(TAG_OK_Y_BTN);

        ok_extent_btn.setOnClickListener(new ClickListeners());
        ok_extent_btn.setTag(TAG_OK_EXTENT_BTN);

        //加速度传感器管理者
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //加速度传感器实例
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        float ACCEL_X_MID = sph.getSP_float("BI","ACCEL_X","0.0");
        float ACCEL_Y_MID = sph.getSP_float("BI","ACCEL_Y","0.0");
        accel_old_data_tv.append("已设置的加速度数据：X方向："+ACCEL_X_MID
                +"   "+"Y方向："+ACCEL_Y_MID);

        extent_seekBar.setMax(100);
        float ACCEL_EXTENT_MID = sph.getSP_float("BI","ACCEL_EXTENT","1.8");
        extent_seekBar.setProgress( (int)ACCEL_EXTENT_MID*10 );
        extent_seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override//进度改变时触发
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                ACCELEROMETER_EXTENT = ((float) progress)/ 10;
                ok_extent_btn.setText("设置"+
                        ACCELEROMETER_EXTENT+
                        "为自动转弯幅度（默认2.2，不可小于0.2）");
            }

            @Override//进度按下时触发
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override//进度松开时触发
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    // 传感器返回的数据
    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        ACCELEROMETER_X = Float.parseFloat(new DecimalFormat(".0").format(values[0]));
        ACCELEROMETER_Y = Float.parseFloat(new DecimalFormat(".0").format(values[1]));
        ACCELEROMETER_Z = Float.parseFloat(new DecimalFormat(".0").format(values[2]));

        //用来显示加速度
        accel_data_tv.setText("X方向：" + ACCELEROMETER_X + "\n" +
                "Y方向：" + ACCELEROMETER_Y + "\n" +
                "Z方向：" + ACCELEROMETER_Z + "\n");
    }

    private class ClickListeners implements View.OnClickListener{
        public void onClick(View v){
            new ClickFeedbackHelper().feedback(v, SsCalibrateActivity.this);

            int key = 0;
            if(v.getTag()!=null){
                key = (Integer) v.getTag();
            }
            switch (key){
                case 1://返回上一页
                    finish();
                    Log.d(TAG,"quit");
                    break;
                case 2://设置X
                    sph.saveSP_float("BI",
                                    "ACCEL_X",
                                    ACCELEROMETER_X);
                    SingleToast.getInstance(SsCalibrateActivity.this).show("X方向成功设置为" + ACCELEROMETER_X);
//                    restart_stv.setVisibility(View.VISIBLE);//更改重启按钮可见性
                    remindRestart(v);
                    break;
                case 3://设置Y
                    sph.saveSP_float("BI",
                                    "ACCEL_Y",
                                    ACCELEROMETER_Y);
                    SingleToast.getInstance(SsCalibrateActivity.this).show("Y方向成功设置为" + ACCELEROMETER_Y);
//                    restart_stv.setVisibility(View.VISIBLE);//更改重启按钮可见性
                    remindRestart(v);
                    break;
                case 4://设置幅度
                    //如果转弯幅度小于0.2，则相当于设置不生效
                    sph.saveSP_float("BI",
                                    "ACCEL_EXTENT",
                            ACCELEROMETER_EXTENT>(float)0.2 ? ACCELEROMETER_EXTENT: (float) 2.2);
                    SingleToast.getInstance(SsCalibrateActivity.this).show(
                            "转弯幅度成功设置为" +
                                    (ACCELEROMETER_EXTENT>(float)0.2 ? ACCELEROMETER_EXTENT: (float) 2.2));
//                    restart_stv.setVisibility(View.VISIBLE);//更改重启按钮可见性
                    remindRestart(v);
                    break;
                case 5://重启APP
                    pubVari.restart(SsCalibrateActivity.this, SsCalibrateActivity.this);
                    break;
                default:
                    break;
            }
        }
    }

    //继承传感器接口的必要方法
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    protected void onResume(){
        super.onResume();
        //添加（注册）加速度监听器
        if(sensorManager != null){
            sensorManager.registerListener(
                    (SensorEventListener) this,
                    sensor,SensorManager.SENSOR_DELAY_UI);

//            sensorManager.registerListener((SensorListener) this, SensorManager.SENSOR_ORIENTATION
//                            | SensorManager.SENSOR_ACCELEROMETER,
//                    200000);//设置采样率
        }
    }

    protected void onPause(){
        //解除加速度传感器的监听
        if(sensorManager != null){
            sensorManager.unregisterListener((SensorEventListener) this,sensor);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        //解除监听
        if(sensorManager != null){
            sensorManager.unregisterListener((SensorEventListener) this,sensor);
        }
        super.onDestroy();
    }


    public void remindRestart(View v){
        if (!SHOW_REMIND_RESTART){
            new QMUIDialog.MessageDialogBuilder(SsCalibrateActivity.this)
                    .setTitle("提示")
                    .setMessage("设置变更后需要重启APP生效，现在重启吗？")
                    .addAction("稍后", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            new ClickFeedbackHelper().feedback(v, SsCalibrateActivity.this);
                            dialog.dismiss();
                            SHOW_REMIND_RESTART = false;
                        }
                    })
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            new ClickFeedbackHelper().feedback(v, SsCalibrateActivity.this);
                            dialog.dismiss();
                            SHOW_REMIND_RESTART = false;
                            pubVari.restart(SsCalibrateActivity.this,SsCalibrateActivity.this);
                        }
                    })
                    .show();
            SHOW_REMIND_RESTART = true;
        }
    }
}

